----------- 
-- Author: Bojun Chen
-- Date: 2021-09-14 17:50:46
-- Desc: class
----------- 


--[[
    @desc: 深克隆一个table
    author:Bojun Chen
    time:2021-09-15 14:39:23
    --@tab: 需要克隆的table
    @return: 克隆后的table
]]
function DeepClone(tab)
    if next(tab) == nil then return end

    local tempTb = {}
    for k, v in pairs(tab) do
        local key
        local val
        if type(k) == 'table' then
            key = DeepClone(k)
        else
            key = k
        end
        if type(v) == 'table' then
            val = DeepClone(v)
        else
            val = v
        end
        tempTb[key] = val
    end

    local metaTab = getmetatable(tab)
    setmetatable(tempTb, metaTab)

    return tempTb
end



--[[
    @desc: class函数，模拟面向对象
    author:Bojun Chen
    time:2021-09-14 17:51:09
    --@name: class名字
	--@super: 父节点
    @return: class实例
]]
function class(name, super)
    local cls = {}

    local superType = type(super)
    if superType == 'table' then
        setmetatable(cls, { __index = super })
        cls.__ctype = 1 -- 继承table
    elseif  superType == 'function' or superType == 'userdata' then
        setmetatable(cls, { __index = super })
        cls.__ctype = 2 -- 继承function或者userdata
    else
        cls.__ctype = 3 -- 无继承
    end
    
    cls.super = super
    cls.__cname = name

    -- 构造
    function cls:ctor(...) end

    -- 实例化
    function cls.new(...)
        local o = {}
        setmetatable(o, {__index = cls})

        -- 递归执行父类的构造
        local create
        create = function (tab, ...)
            local super = tab.super
            if type(super) == 'table' then
                create(super, ...)
            end

            if type(tab.ctor) == 'function' then
                tab.ctor(o, ...)
            end
        end

        create(o, ...)

        return o
    end

    return cls
end

